﻿using System;
using System.Xml.Linq;
using System.Linq;

namespace FluentlyXml.Core.Deserialization.BuiltInDeserializers
{
	internal class ArrayDeserializer : ITypeDeserializer
	{
		public bool CanDeserialize(Type type)
		{
			return type.IsArray;
		}

		public object Deserialize(Type target, XElement element, IDeserializationContext context)
		{
			var elements = element.Elements().ToArray();

			var elementType = target.GetElementType();

			Array array = Array.CreateInstance(elementType, elements.Length);

			for (int i=0; i < elements.Length; i++)
			{
				var item = context.Deserialize(elementType, elements[i], context);
				array.SetValue(item, i);
			}

			return array;
		}

		public object GetIdentityFor(object obj)
		{
			return obj;
		}
	}
}